/**
 * Created by shenc on 2017/9/7.
 */

//数组查询
if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}
//数组去重
Array.prototype.unique = function(){
    var res = [];
    var json = {};
    for(var i = 0; i < this.length; i++){
        if(!json[this[i]]){
            res.push(this[i]);
            json[this[i]] = 1;
        }
    }
    return res;
};
//csrf 验证
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});


$(document).ready(function(){
    //初始化页面
    Details.initPage();
});

var Details = {
    resizeTimer:0,//屏幕尺寸变化延时计算bd高度
    isLoading:false,
    checkboxNum:null,//多选题的数量
    /**
     * 绑定基础的页面内容
     */
    initPage:function(){
        var self = this;
        var localData=window.localStorage.getItem('exam_form');


        scrollTo(0,0);
        self.setHeight();
        self.checkLogin();

        //清空历史分数
        window.localStorage.setItem('exam_record_id','');

        localData&&self.getLocal(localData);//缓存数据赋值
        self.initTimer();//显示倒计时
        self.initEvent();//绑定页面事件

    },

    setHeight:function () {
        var self=this;
        var bd=$('.bd');
        var winH=$('html').height();
        var hdH=$('.hd').height();
        var ftH=$('.ft').height();

        clearTimeout(self.resizeTimer);
        self.resizeTimer=setTimeout(function () {
            bd.css('height',winH-hdH);
            //bd.find('.section').find('.weui-btn_warn:last').css('margin-bottom',ftH+10);
        },300);

    },
    
    /**
     * 绑定基础的页面事件
     */
    initEvent:function(){
        var self = this;
        var bd=$('.bd');

        //重置高度
        $(window).resize(function() {
            console.log(1111);
            setTimeout(function () {
                self.setHeight();
            },100);
        });

        //下一页事件：从单选到多选页面
        $("#nextPage1").click(function() {
            $('.section1').removeClass('on');
            $('.section2').addClass('on');
            // var get_cache_form = window.localStorage.getItem('exam_form');
            // if(get_cache_form){
            //     说明有本地缓存,为中途退出
                // self.getLocal(get_cache_form);
            // }
            bd.scrollTop(0);
        });

        //下一页事件：从多选到判断页面
        $("#nextPage2").click(function() {
            $('.section2').removeClass('on');
            $('.section3').addClass('on');
            bd.scrollTop(0);
        });

        //上一页事件：从多选到单选
        $("#prevPage1").click(function() {
            $('.section1').addClass('on');
            $('.section2').removeClass('on');
            bd.scrollTop(0);
        });
        //上一页事件：从判断到多选
        $("#prevPage2").click(function() {
            $('.section2').addClass('on');
            $('.section3').removeClass('on');
            bd.scrollTop(0);
        });

        //确认提交
        $("#submitBtn").click(function() {
            var msg=self.checkQuestin();
            var user = self.checkLogin();

            //如果没有登录，调转到首页
            if(!user){
                return false;
            }

            //提交数据到后台
            $.confirm({
                title: '温馨提示',
                text: msg||"您确定要提交吗?",
                onOK: function () {
                    //点击确认
                    if(self.isLoading) return false;
                    self.isLoading=true;
                    self.saveUserTmp();
                },
                onCancel: function () {
                    //取消操作
                }
            });

        });

        //统一接受表单变化事件
        $('#exam_form').find("input").change(function () {
            //缓存表单数据
            //var value = $.trim($(this).offsetParent().find(".weui-cell__bd").text());
            var o = {};
            var a = $('#exam_form').serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            console.log(JSON.stringify(o));
            window.localStorage.setItem('exam_form', JSON.stringify(o));
        });
    },

    /**
     * 提交分数和本地数据到服务器上
     */
    saveUserTmp:function () {
        var self=this;

        var exam_form = window.localStorage.getItem('exam_form');
        var minute = window.localStorage.getItem('exam_form_minute');
        var user = window.localStorage.getItem('exam_user_info');

        $.showLoading();
        $.ajax({
            type: "post",
            async:false,
            url: "/exam",
            dataType: "json",
            data:{'user':user,'exam_form':exam_form},
            success: function(res) {
                if(res.code){
                    window.localStorage.setItem('exam_form','');
                    window.localStorage.setItem('exam_form_minute','');
                    window.localStorage.setItem('exam_record_id',res.id);

                    if(minute&&minute>0){
                        self.jump('/score');
                    }else{
                        setTimeout(function () {
                            self.jump('/score');
                        },60*1000);
                    }

                }else{
                    $.toptip(res.message);
                }
            },
            error:function () {
                $.toptip('请求超时');
            },
            complete:function () {
                $.hideLoading();
                setTimeout(function () {
                    self.isLoading=false;
                },500);
            }
        });
    },

    jump:function (href) {
        if (!href) {
            return;
        }
        if (href && /^#|javasc/.test(href) === false) {
            if (history.replaceState) {
                history.replaceState(null, document.title, href.split('#')[0] + '#');
                location.replace('');
            } else {
                location.replace(href);
            }
        }
    },

    /**
     * 获取本地缓存的值
     */
    getLocal:function(data){
        var self = this;
        try {
            data = JSON.parse(data);
            $('#exam_form').find("input").each(function(i){
                var $form_ele = $(this);
                //通过获取表单元素name属性值，来获取缓存数据对应的value值
                var input_name = $form_ele.attr('name');
                //遍历json数据对象data，获取value值
                var dateValue = data[input_name];
                var input_val = $form_ele.val();
                //var input_val = $.trim($form_ele.offsetParent().find(".weui-cell__bd").text());
                if(dateValue){
                    if(typeof (dateValue) == "string"){
                        //单选框事件
                        if( input_val == dateValue){
                            $form_ele.attr("checked",'checked');
                        }
                    }else{
                        //复选框事件
                        for(var j = 0; j<dateValue.length;j++){
                            if( input_val == dateValue[j]){
                                $form_ele.attr("checked",'checked');
                            }
                        }
                    }
                }
            });
        } catch (e) {
            console.log(e.stack + 'JSON.parse()解析参数出错');
        }
    },

    initTimer:function(){
        var self = this;
        var t = 0;
        var timer = 0;
        var showItem=$('#timer');
        var minute = window.localStorage.getItem('exam_form_minute');
        if(!minute){
            minute=30*60*1000;//毫秒
        }

        var start = function (minute) {
            timer = setInterval(function () {
                t = t + 1000;
                var txt=showTime((minute - t));
                showItem.text(txt);
                window.localStorage.setItem('exam_form_minute',minute-t);
                if ((minute - t) <= 0) {
                    clearInterval(timer);
                    self.isLoading=true;
                    self.saveUserTmp();//提交表单

                    $.modal({
                        title: "温馨提示",
                        text: "您的答题时间已到，系统已经自动提交",
                        buttons: [{ text: "确认", onClick: function(){
                            window.localStorage.setItem('exam_form','');
                            window.localStorage.setItem('exam_form_minute','');
                            self.jump('/score?id='+window.localStorage.getItem('exam_record_id'));
                        } }]
                    });

                    return true;

                }

            }, 1000);
        };

        //开始倒计时
        minute&&start(minute);

        //数字前面补0
        function PrefixInteger(num, length) {
            return (Array(length).join('0') + num).slice(-length);
        }

        //格式化数字显示效果
        function showTime(ms) {
            var m = Math.floor(ms / 1000 / 60 % 60),
                s = Math.floor(ms / 1000 % 60);
            return  PrefixInteger(m,2) + ":" + PrefixInteger(s,2);
        }
    },

    /*
    * 检查题目是否已做
    */
    checkQuestin:function () {
        var self=this;
        var form=$('#exam_form');
        var arr1=[],arr2=[],arr3=[],okArr=[];
        var inputsChecked=form.find('input:checked');
        var inputs=form.find('input');

        for(var i=0;i<inputsChecked.length;i++){
            var input=inputsChecked.eq(i),name=input.attr('name');
            okArr.push(name);
        }
        okArr=okArr.unique();

        for(var j=0;j<inputs.length;j++){
            var a=inputs.eq(j),bname=a.attr('name');

            if(okArr.indexOf(bname)==-1){
                if(a.closest('.section1').length){
                    arr1.push(bname);
                }else if(a.closest('.section2').length){
                    arr2.push(bname);
                }else if(a.closest('.section3').length){
                    arr3.push(bname);
                }
            }
        }

        arr1=arr1.unique();
        arr2=arr2.unique();
        arr3=arr3.unique();
        var msg=[];
        if(arr1.length){
            msg.push(arr1.length+'道单选题');
        }

        if(arr2.length){
            msg.push(arr2.length+'道多选题');
        }

        if(arr3.length){
            msg.push(arr3.length+'道判断题');
        }

        if(arr1.length+arr2.length+arr3.length==20){
            msg='您还没有答题，确定要提交吗？';
        }else if(msg.length){
            msg=msg.join(',');
            msg+='未做，您确定要提交吗？';
        }else{
            msg='';
        }

        return msg;
    },

    /**
     * 验证登录 **/
    checkLogin:function () {
        var user = window.localStorage.getItem('exam_user_info');

        //如果没有登录，调转到首页
        if(!user){
            $.alert({
                title: '温馨提示',
                text: "请输入用户信息",
                onOK: function () {
                    //点击确认
                    location.href="/";
                }
            });
            return false;
        }else{
            return true;
        }
    }



};